package com.hyperfix.common.service.impl;

import com.hyperfix.common.exception.CustomException;
import com.hyperfix.common.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @author JiangChunYu
 * 2023/3/16
 */
@Slf4j
@Service
public class MailServiceImpl implements MailService {
    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String from;

    @Value("${spring.mail.username}")
    private String developerEmail;

    @Async
    @Override
    public void sendEmailToUser(String to, String templateName, Map<String, Object> values) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false);
            mimeMessageHelper.setFrom(from, "西南石油大学本科毕业设计-姜春雨");
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject("油气集输站中心监控系统邮件服务");
            // 创建正文
            Context context = new Context();
            context.setVariables(values);
            String content = templateEngine.process(templateName, context);
            mimeMessageHelper.setText(content, true);
            javaMailSender.send(mimeMessage);
            log.info("向{}成功发送了邮件", to);
        } catch (MessagingException | UnsupportedEncodingException e) {
            throw new CustomException("邮件发送失败！");
        }
    }

    @Override
    public void sendEmailToDeveloper(String ip, String uri, String errMsg, String stackTrace) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(developerEmail);
        simpleMailMessage.setSubject("油气集输站中心监控系统未知错误日志记录");
        simpleMailMessage.setText(ip + "\n\n" + uri + "\n\n" + errMsg + "\n\n" + stackTrace);
        javaMailSender.send(simpleMailMessage);
    }
}
